<?php
// +----------------------------------------------------------------------
// | 中联致远服务端框架
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://www.zhongliansoft.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: tony <tanyu@zhongliansoft.com>
// +----------------------------------------------------------------------

namespace app\common\model;

use think\Validate;
use think\model\concern\SoftDelete;
use think\Facade\Log;

class WxDsBill extends Common
{
    /**
     * @param $post
     *
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function tableData($post)
    {
        if (isset($post['limit'])) {
            $limit = $post['limit'];
        } else {
            $limit = config('paginate.list_rows');
        }

        $tableWhere = $this->tableWhere($post);
        $list = $this->field($tableWhere['field'])->where($tableWhere['where'])->order($tableWhere['order'])->paginate($limit);
        $data = $this->tableFormat($list->getCollection());         //返回的数据格式化，并渲染成table所需要的最终的显示数据类型

        $re['code'] = 0;
        $re['msg'] = '';
        $re['count'] = $list->total();
        $re['data'] = $data;

        return $re;
    }

    /**
     *  添加品牌
     * User:tony
     * @param $data
     * @return array
     */
    public function addData($data)
    {
        $result = [
            'status' => true,
            'msg' => '保存成功',
            'data' => [],
            'token'  => \think\facade\Request::token('__ZlServer_Token__', 'sha1')
        ];

        if (!$this->allowField(true)->save($data)) {
            $result['status'] = false;
            $result['msg'] = '保存失败';
        }

        return $result;
    }

    //where搜索条件
    protected function tableWhere($post)
    {
        $where = [];
        if (isset($post['order_sn_sh']) && $post['order_sn_sh'] != "") {
            $where[] = ['order_sn_sh', 'like', '%' . $post['order_sn_sh'] . '%'];
        }
        if (isset($post['pay_status']) && $post['pay_status'] != "") {
            $where[] = ['pay_status', 'eq', $post['pay_status']];
        }
        if (isset($post['time']) && $post['time'] != "") {
            $date_array = explode('到', $post['time']);
            $sutime = trim($date_array[0]) . ' 00:00:00';
            $eutime = trim($date_array[1]) . ' 23:59:59';
            $where[] = ['pay_time', ['EGT', $sutime], ['ELT', $eutime], 'and'];
        }
        $result['where'] = $where;
        $result['field'] = "*";
        $result['order'] = ['pay_time DESC'];
 
        return $result;
    }

    /**
     * @param $list
     *
     * @return mixed
     */
    protected function tableFormat($list)
    {
        foreach($list as $k => $v){
            if(isset($v['refund_number_wx'])){
                if(trim($v['refund_number_wx']) == '0') {
                    $v['refund_number_wx'] = '';
                }
            }
            if(isset($v['refund_number_sh'])){
                if(trim($v['refund_number_sh']) == '0') {
                    $v['refund_number_sh'] = '';
                }
            }
        }
        return $list;
    }

    public function dobilling($date)
    {
        $payment_code = 'wechatpay';
        
        ///判断支付方式是否开启
        $paymentsModel = new Payments();
        $paymentInfo = $paymentsModel->getPayment($payment_code, $paymentsModel::PAYMENT_STATUS_YES);
        if(!$paymentInfo){
            return error_code(10050);
        }
        $conf = json_decode($paymentInfo['params'],true);
        // 开始微信对账
        $payment = \org\Payment::create($payment_code, $conf);
        $billInfo = $payment->getDsBill($date);

        if($billInfo['status']) {
            $this->updateBillInfo($date, $billInfo['data']);
        }
    }

    /**
     * @param $date
     * @param $billInfo
     *
     * @return mixed
     */
    public function updateBillInfo($date, $billInfo)
    {
        // 数据格式化
        $billList = $this->deal_WeChat_response($billInfo);

        if(count($billList['bill']) > 0) {
            // 清理数据
            $sutime = trim($date) . ' 00:00:00';
            $eutime = trim($date) . ' 23:59:59';
            $where[] = ['pay_time', ['EGT', $sutime], ['ELT', $eutime], 'and'];
            $this->where($where)->delete();
            
            // 插入数据 每次100条
            $this->startTrans(); 

            $tmpData = [];
            $num = 0;
            foreach ($billList['bill'] as $val) {
                $tmpData[] = $val;
                $num++;
                if($num == 100) {
                    $this->insertAll($tmpData);  
                    $tmpData = [];
                    $num = 0;
                }
            }    
            
            if(count($tmpData) > 0) {
                $this->insertAll($tmpData);  
            }

            $this->commit(); 
        }
    }

    /**
     * 微信对账单数据处理
     * @param $response 对账单数据
     * @return array 返回结果
     */
    private function deal_WeChat_response($billInfo)
    {
        $result  = array();
        $billInfo = str_replace(",", " ", $billInfo);
        $billInfo = explode(PHP_EOL, $billInfo);

        foreach ($billInfo as $key => $val) {
            if (strpos($val, '`') !== false) {
                $data = explode('`', $val);
                array_shift($data); // 删除第一个元素并下标从0开始
              
                if (count($data) == 24) { // 处理账单数据
                    //if (strpos($data[6], 'zl') !== false) {
                        $result['bill'][] = array(
                            'pay_time'          => $data[0], // 支付时间
                            'APP_ID'            => $data[1], // app_id
                            'MCH_ID'            => $data[2], // 商户id
                            'SUB_MCH_ID'        => $data[3], // 子商户id
                            'IMEI'              => $data[4], // 设备号
                            'order_sn_wx'       => $data[5], // 微信订单号
                            'order_sn_sh'       => $data[6], // 商户订单号
                            'user_tag'          => $data[7], // 用户标识
                            'pay_type'          => $data[8], // 交易类型
                            'pay_status'        => $data[9], // 交易状态
                            'bank'              => $data[10], // 付款银行
                            'money_type'        => $data[11], // 货币种类
                            'total_amount'      => $data[12], // 总金额
                            'coupon_amount'     => $data[13], // 代金券或立减优惠金额
                            'refund_number_wx'  => $data[14], // 微信退款单号
                            'refund_number_sh'  => $data[15], // 商户退款单号
                            'refund_amount'     => $data[16], // 退款金额
                            'coupon_refund_amount' => $data[17], // 代金券或立减优惠退款金额
                            'refund_type'       => $data[18], // 退款类型
                            'refund_status'     => $data[19], // 退款状态
                            'goods_name'        => $data[20], // 商品名称
                            'MCH_ATTACH'        => $data[21], // 商户数据包
                            'service_charge'    => $data[22], // 手续费
                            'rate'              => $data[23], // 费率 
                        );
                    //}
                } else if (count($data) == 27) { // 处理账单数据
                    //if (strpos($data[6], 'zl') !== false) {
                        $result['bill'][] = array(
                            'pay_time'          => $data[0], // 支付时间
                            'APP_ID'            => $data[1], // app_id
                            'MCH_ID'            => $data[2], // 商户id
                            'SUB_MCH_ID'        => $data[3], // 子商户id
                            'IMEI'              => $data[4], // 设备号
                            'order_sn_wx'       => $data[5], // 微信订单号
                            'order_sn_sh'       => $data[6], // 商户订单号
                            'user_tag'          => $data[7], // 用户标识
                            'pay_type'          => $data[8], // 交易类型
                            'pay_status'        => $data[9], // 交易状态
                            'bank'              => $data[10], // 付款银行
                            'money_type'        => $data[11], // 货币种类
                            'total_amount'      => $data[12], // 总金额
                            'coupon_amount'     => $data[13], // 代金券或立减优惠金额
                            'refund_number_wx'  => $data[14], // 微信退款单号
                            'refund_number_sh'  => $data[15], // 商户退款单号
                            'refund_amount'     => $data[16], // 退款金额
                            'coupon_refund_amount' => $data[17], // 代金券或立减优惠退款金额
                            'refund_type'       => $data[18], // 退款类型
                            'refund_status'     => $data[19], // 退款状态
                            'goods_name'        => $data[20], // 商品名称
                            'MCH_ATTACH'        => $data[21], // 商户数据包
                            'service_charge'    => $data[22], // 手续费
                            'rate'              => $data[23], // 费率 
                            'rate'              => $data[23], // 费率 
                            'order_amount'      => $data[24], // 订单金额
                            'apply_refund_amount' => $data[25], // 申请退款金额
                            'rate_desc'         => $data[26], // 费率备注 
                        );
                    //}
                }

                if (count($data) == 5) { // 统计数据
                    $result['summary'] = array(
                        'order_num'    => $data[0],  // 总交易单数
                        'turnover'    => $data[1],  // 总交易额
                        'refund_turnover' => $data[2],  // 总退款金额
                        'coupon_turnover' => $data[3],  // 总代金券或立减优惠退款金额
                        'rate_turnover'  => $data[4],  // 手续费总金额
                    );
                } else if (count($data) == 7) { // 统计数据
                    $result['summary'] = array(
                        'order_num'    => $data[0],  // 总交易单数
                        'turnover'    => $data[1],  // 总交易额
                        'refund_turnover' => $data[2],  // 总退款金额
                        'coupon_turnover' => $data[3],  // 总代金券或立减优惠退款金额
                        'rate_turnover'  => $data[4],  // 手续费总金额
                        'order_turnover' => $data[5],  // 订单总金额
                        'apply_refund_turnover'  => $data[6],  // 申请退款总金额
                    );
                }
            }
        }

        return $result;
    }
    
    /**
     * 获取csv数据
     * @param $post
     * @return array
     */
    public function getDsExportData($post)
    {
        $result   = [
            'status' => false,
            'data'   => [],
            'msg'    => '无可导出用户'
        ]; 
 
        $where = [];

        if (isset($post['order_sn_sh']) && $post['order_sn_sh'] != "") {
            $where[] = ['order_sn_sh', 'like', '%' . $post['order_sn_sh'] . '%'];
        }
        if (isset($post['pay_status']) && $post['pay_status'] != "") {
            $where[] = ['pay_status', 'eq', $post['pay_status']];
        }
        if (isset($post['time']) && $post['time'] != "") {
            $date_array = explode('到', urldecode($post['time']));
            $sutime = trim($date_array[0]) . ' 00:00:00';
            $eutime = trim($date_array[1]) . ' 23:59:59';
            $where[] = ['pay_time', ['EGT', $sutime], ['ELT', $eutime], 'and'];
        }

        $list = $this->where($where)->order('pay_time DESC')->select();
        if (count($list) > 0) {
            $result['status'] = true;
            $result['msg']    = '导出成功';
            $result['data']   = $list;
            return $result;
        } else {
            //失败，导出失败
            return $result;
        }
    }
}
